﻿using IOP.AspNetCore.Extension.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace IOP.AspNetCore.Extension.Error
{
    /// <summary>
    /// 错误回执中间件
    /// </summary>
    public class ErrorResponseMiddleware
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ErrorResponseMiddleware> _Logger;
        /// <summary>
        /// 管线委托
        /// </summary>
        private readonly RequestDelegate _next;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        /// <param name="logger"></param>
        public ErrorResponseMiddleware(RequestDelegate next, ILogger<ErrorResponseMiddleware> logger)
        {
            _Logger = logger;
            _next = next;
        }

        /// <summary>
        /// 执行管线
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
                if (context.Response.StatusCode == 401)
                {
                    context.Response.Clear();
                    await context.ReturnBadRequestAsync("无权访问", 401);
                    return;
                }
                if (context.Response.StatusCode == 404)
                {
                    context.Response.Clear();
                    await context.ReturnBadRequestAsync("该请求路径不存在", 404);
                    return;
                }
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message + e.StackTrace);
                if (context.Response.HasStarted) throw;
                context.Response.Clear();
                await context.ReturnBadRequestAsync(e.Message, 500);
                return;
            }
        }
    }
}
